const express = require('express');
const router = express.Router();
const {Article} = require("../../models");
const {Op} = require('sequelize')
const {NotFoundError, success, failure} = require('../../utils/response')
/* GET home page. */
/*
* 查询所有文章接口
* */
//白名单过滤
const whitelistFiltering = (req) => {
    return {
        title: req.body.title,
        content: req.body.content
    }
}

// 根据id获取文章
async function getArticle(req) {
    //获取文章id
    const {id} = req.params;
    //查询当前文章
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID:${id}的文章未找到`)
    }
    return article
}

// 获取文章列表
router.get('/', async function (req, res, next) {
    try {
        const query = req.query

        // 定义当前页面变量当前第几页
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        //定义每页显示多少条数据
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        //计算offset
        const offset = (currentPage - 1) * pageSize
        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        }
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            }
        }
        // findAll 导入 Article 模型查询所有文章并按 id 降序排列
        //findAndCountAll 定义一个函数用于查找并计数所有符合条件的记录
        const {count, rows} = await Article.findAndCountAll(condition);
        success(res, "查询文章列表成功", {
            articles: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error);
    }
});

// 根据id获取文章
router.get("/:id", async function (req, res, next) {
    try {
        const article = await getArticle(req)
        success(res, "查询文章成功", {article})
    } catch (error) {
        failure(res, error);
    }
});

// 创建文章
router.post("/", async function (req, res, next) {
    try {
        //白名单过滤
        const body = whitelistFiltering(req)
        // 使用 Article 模型创建新的文章实例
        const article = await Article.create(body);
        success(res, "创建文章成功", {article}, 201)
    } catch (error) {
        failure(res, error);
    }
});
// 删除文章
router.delete('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req)
        // 销毁（删除）文章对象
        await article.destroy()
        success(res, "删除文章成功")
    } catch (e) {
        failure(res, error);
    }
})

//更新文章
router.put('/:id', async function (req, res, next) {
    try {
        const article = await getArticle(req)
        const body = whitelistFiltering(req)
        await article.update(body);
        success(res, "更新文章成功", {article},)
    } catch (e) {
        failure(res, error);
    }
})
module.exports = router;
